package com.sso.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: TongRui乀
 * @Date: 2020-03-23 15:13
 * @description：  登录认证失败的处理逻辑
 */
@Slf4j
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败，进入登录失败的处理器-------LoginFailureHandler");

        HashMap<String, String> map = new HashMap<>();

        map.put("code", "1001");
        map.put("message", "登录失败，请检查用户名或密码是否有误！");

        response.setContentType("application/json;charset=utf-8");
        response.getOutputStream().write(objectMapper.writeValueAsBytes(map));


    }
}
